<?php
/**
 * @author    Medard <pingguoli@gmail.com>
 * @date      2019/3/8 10:10
 * @copyright Copyright 2018 - 2019
 *  
 *  
 * @version   1.0
 */

namespace App\Http\Controllers\Admin;


use App\models\Alert;
use App\Models\File;
use App\Support\ChunkUpload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
/**
 * 公共类
 * Class CommonController
 * @package App\Http\Controllers\Admin
 */
class AlertController extends BaseController
{

    /**
     * 记录报警
     *  http://localhost:8123/admin/alert/alert
     *
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function alert(Request $request)
    {
        $validate = [
            'img' => 'image',
            'pid' => 'required',
            'content' => 'required',
            'time_stamp' => 'required|numeric'
        ];

        $this->validate($request, $validate, [], [
            'img' => "图片",
            'content' => "报警信息",
            'pid' => "摄像头编号",
            'time_stamp' => "时间戳"
        ]);

        $data = $request->only(['img', 'content', 'pid', 'time_stamp']);

        if ($request->hasFile('img')) {
            $file = $request->file('img');
            $uploader = new ChunkUpload();
            $filePath = $uploader->setType('image')->upload($file);
            if ($filePath === false) {
                return back()->withErrors(['img' => __('Img upload failed')])->withInput();
            }
            $data['img'] = $filePath;
        }

        if (Alert::insert($data)) {
            return response()->json(['code'=>200, 'msg'=>"success"]);
        }

        Log::error("save false".json_encode($data));

        return response()->json(['code'=>102, 'msg'=>"error"]);

    }
}